<template>
	<xn-form-container
		:title="formData.id ? '编辑' : '新增'"
		width="1000"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form
			:wrapper-col="{ span: 16 }"
			:label-col="{ span: 8 }"
			autocomplete="off"
			labelAlign="right"
			ref="formRef"
			:model="formData"
			:rules="formRules"
		>
			<a-row>
				<a-col :span="12">
					<a-form-item label="转出仓库" name="warehouseSourceId">
						<xn-page-selector
							ref="warehouseSourceRef"
							:field-names="{ label: 'warehouseName', value: 'id' }"
							:page-function="(param) => storeCenterApi.getPage(param)"
							v-model:value="formData.warehouseSourceId"
							placeholder="请选择仓库"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="转入仓库" name="warehouseTargetId">
						<xn-page-selector
							ref="warehouseTargetRef"
							:field-names="{ label: 'warehouseName', value: 'id' }"
							:page-function="(param) => storeCenterApi.getPage(param)"
							v-model:value="formData.warehouseTargetId"
							placeholder="请选择仓库"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="备注">
						<a-textarea
							:autosize="{ minRows: 2, maxRows: 2 }"
							v-model:value="formData.remark"
							placeholder="请输入备注"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="24">
					<a-button type="primary" class="childAddButton" @click="addProduct()">
						<PlusOutlined />
						新增
					</a-button>
					<a-popconfirm title="是否删除?" @confirm="removeGoods()">
						<a-button style="margin-left: 12px" type="remove" danger>
							<LineOutlined />
							删除
						</a-button>
					</a-popconfirm>

					<a-table
						:row-selection="options.rowSelection"
						:pagination="false"
						:columns="goodsColumns"
						:data-source="formData.proWaresTransferDetailList"
						:scroll="{ x: 700 }"
					>
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'remark'">
								<div class="editable-cell">
									<a-input v-model:value="record.remark" />
								</div>
							</template>
							<template v-if="column.dataIndex === 'transferNum'">
								<div class="editable-cell">
									<a-input v-model:value="record.transferNum" />
								</div>
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
		</template>
	</xn-form-container>

	<productSelector
		:data-provider="getStockTransGoodsList"
		:columns="selectorColumns"
		@onProductChange="onSelectProductChange"
		ref="productsRef"
	/>
</template>

<script setup name="stockTransferForm">
	import { required } from '@/utils/formRules'
	import bizTool from '@/utils/bizTool'
	import { message } from 'ant-design-vue'
	import storeCenterApi from '@/api/base_data/storeCenterApi'
	import stockTrasnferApi from '@/api/warehouse/stockTrasnferApi'
	import warehouseApi from '@/api/warehouse/warehouseApi'
	import productSelector from '@/components/Selector/productSelector.vue'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	const productsRef = ref()
	const warehouseSourceRef = ref()
	const warehouseTargetRef = ref()
	const formData = ref({})
	const submitLoading = ref(false)
	// 打开抽屉
	const onOpen = (record) => {
		formData.value = {}
		visible.value = true
		if (record) {
			formData.value = { ...record }
			loadDetail(record.id)
		}
		nextTick(() => {
			warehouseTargetRef.value.onPage({})
			warehouseSourceRef.value.onPage({})
		})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const selectedRowKeys = ref([])

	const removeGoods = () => {
		let datas = formData.value.proWaresTransferDetailList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
	}

	const addProduct = () => {
		if (!formData.value.warehouseSourceId) {
			message.error('请选择转出仓库')
		} else {
			productsRef.value.showDialog(formData.value.proWaresTransferDetailList)
		}
	}

	const onSelectProductChange = (items) => {
		items.forEach((it) => {
			let find = (formData.value.proWaresTransferDetailList || []).find((element) => {
				return element['key'] == it['key']
			})
			if (find) {
				it['transferNum'] = find['transferNum']
			}
		})
		formData.value.proWaresTransferDetailList = [].concat(items)
	}

	const loadDetail = (id) => {
		stockTrasnferApi
			.detail({
				id: id
			})
			.then((res) => {
				formData.value.proWaresTransferDetailList = res.proWaresTransferDetailList.map((it) => {
					if (it.proMaterial) {
						it['category'] = '物料'
						it['materialName'] = it['proMaterial'].name
						it['code'] = it['proMaterial']['code']
						it['waresPrice'] = it['proMaterial'].unitPrice
						it['unit'] = it['proMaterial'].unit
						it['spec'] = it['proMaterial'].spec
						it['key'] = it['materialId']
						it['unitPrice'] = it['materialId'].unitPrice
					} else {
						it['key'] = it['productId']
						it['category'] = '产品'
						it['productNo'] = it['productCode']
						it['product'] = it['productName']
					}
					return it
				})
			})
			.catch(() => {})
	}

	const getStockTransGoodsList = (parameter) => {
		return warehouseApi
			.warehousenumPage(
				Object.assign(parameter, {
					warehouseId: formData.value.warehouseSourceId
				})
			)
			.then((data) => {
				data.records.forEach((it) => {
					let key
					if (it.category == bizTool.productName) {
						key = it['id']
						it['productId'] = it['id']
					} else {
						key = it['materialId']
						it['id'] = it['materialId']
					}
					it['key'] = key
					it['remark'] = ''
				})
				return data
			})
			.catch(() => {})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		warehouseSourceId: [required('请选择转出仓库')],
		warehouseTargetId: [required('请选择转入仓库')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		let params = { ...formData.value }
		let msg = null
		for (let [index, item] of params.proWaresTransferDetailList.entries()) {
			let count = item['transferNum']
			if (!count || count.length <= 0) {
				msg = `第${index + 1}行调拨数量不能为空!`
				break
			}
			let reg = /^[0-9]*$/
			if (!reg.test(count)) {
				msg = `填写内容必须是纯数字`
				break
			}
			if (parseInt(count) <= 0) {
				msg = `第${index + 1}行调拨数量不能小于0!`
				break
			}
		}
		if (msg) {
			message.error(msg)
			return
		}

		formRef.value
			.validate()
			.then(() => {
				if (params.warehouseSourceId == params.warehouseTargetId) {
					message.error('调拨仓库不能相等!')
					return
				}
				submitLoading.value = true
				let amount = 0
				let total = 0
				params.proWaresTransferDetailList.forEach((it) => {
					let transferNum = parseInt(it['transferNum'])
					amount += transferNum * parseFloat(it['waresPrice'])
					total += transferNum
				})
				let detailList = params.proWaresTransferDetailList.map((it) => {
					return {
						materialId: it['materialId'],
						productId: it['productId'],
						transferNum: it['transferNum'],
						waresNum: it['waresNum'],
						waresPrice: it['waresPrice'],
						remark: it['remark']
					}
				})
				if (params.id) {
					params.proWaresTransferDetailEditParamList = detailList
					params.proWaresTransferDetailList = null
				} else {
					params.proWaresTransferDetailList = detailList
				}

				stockTrasnferApi
					.addOrEdit(
						params.id ? 'edit' : 'add',
						Object.assign(params, {
							total: total,
							totalAmount: amount.toFixed(2)
						})
					)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: '50px',
			align: 'center'
		},
		{
			title: '分类',
			width: 100,
			dataIndex: 'category',
			align: 'center',
			ellipsis: true
		},
		{
			title: '编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productNo : record.code
			}
		},
		{
			title: '名称',
			width: 100,
			dataIndex: 'materialName',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.product : record.materialName
			}
		},

		{
			title: '单位',
			width: 100,
			dataIndex: 'unit',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productUnit : record.unit
			}
		},
		{
			title: '型号',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productSpec : record.spec
			}
		},
		{
			title: '库存数量',
			width: 100,
			dataIndex: 'waresNum',
			align: 'center'
		}
	]

	const goodsColumns = [
		{
			title: '分类',
			width: 100,
			dataIndex: 'category',
			align: 'center'
		},
		{
			title: '编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productNo : record.code
			}
		},
		{
			title: '名称',
			width: 100,
			dataIndex: 'materialName',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.product : record.materialName
			}
		},

		{
			title: '单位',
			width: 100,
			dataIndex: 'unit',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productUnit : record.unit
			}
		},
		{
			title: '型号',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.category == bizTool.productName ? record.productSpec : record.spec
			}
		},
		{
			title: '库存数量',
			width: 100,
			dataIndex: 'waresNum',
			align: 'center'
		},
		{
			title: '调拨数量',
			width: 100,
			dataIndex: 'transferNum',
			align: 'center'
		},
		{
			title: '备注',
			width: 130,
			dataIndex: 'remark',
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
